import ts from "typescript"
import path from "path";
import shell from "shelljs";
const transformerFactory: ts.TransformerFactory<ts.SourceFile> = (context:ts.TransformationContext) => {
    const compilerOptions = context.getCompilerOptions();

    // console.log(compilerOptions)
    const compilerHost = ts.createCompilerHost(compilerOptions)

    // 拦截获取文件
    // const originalGetSourceFile = compilerHost.getSourceFile
    // compilerHost.getSourceFile = fileName => {
    //     // 这里可以做类似webpack alias的事情
    //     console.log(fileName)
    //     return originalGetSourceFile.call(compilerHost, fileName)
    // }

// 拦截写入文件
    compilerHost.writeFile = (fileName, data) => {
        // data就是编译生成的js代码
        // console.log("*********************")
        // console.log(fileName, data)
        const dir = path.dirname(fileName);
        const base = path.basename(fileName);
        const newBase = base.replace(/(?:\.jsx?)(.map$|$)/i, ".mjs$1");
        // debug("   * cjs write: %s/{%s => %s}", dir, base, newBase);
        return ts.sys.writeFile(`${dir}/${newBase}`, data);
    }
    // shell.rm('-rf', 'dist');
    return (sourceFile: ts.SourceFile) => {
        // const program = ts.createProgram([sourceFile.fileName], compilerOptions, compilerHost)
        // program.emit()
        function visitor(node: ts.Node): ts.Node {
            return ts.visitEachChild(node, visitor, context);
        }
        return ts.visitEachChild(sourceFile, visitor, context);
    };
};

/** Visits all the nodes of the source file. */
// function visitSourceFile(sourceFile: ts.SourceFile, ctx: ts.TransformationContext) {
//     return (ctx: ts.TransformationContext) => {
//         return (sourceFile: ts.SourceFile) => {
//             function visitor(node: ts.Node): ts.Node {
//                 return ts.visitEachChild(node, visitor, ctx);
//             }
//             return ts.visitEachChild(sourceFile, visitor, ctx);
//         };
//     };
// }
export default transformerFactory